﻿using KwaiXiaoDian.Entity.Common;
using KwaiXiaoDian.Entity.DO;
using KwaiXiaoDian.Entity.VO.Product;
using KwaiXiaoDian.Entity.VO.Notice;
using KwaiXiaoDian.IDao;
using KwaiXiaoDian.IService;
using Microsoft.Extensions.Logging;
using SSharing.Frameworks.NetCore.Common.Extends;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;
using SSharing.Frameworks.NetCore.Common.Results;
using SSharing.Frameworks.NetCore.Common.Consts;
using System.Diagnostics;
using Microsoft.Extensions.Caching.Memory;

namespace KwaiXiaoDian.Service
{
    /// <summary>
    /// 商品店铺信息service
    /// </summary>
    public class ProductShopService : BaseService<TProductShop>, IProductShopService
    {
        private readonly IProductShopDao _productShopDao;
        private readonly IProductService _productService;
        private readonly IKwaiXiaoDianService _kwaiXiaoDianService;
        private readonly ILogger<ProductShopService> _logger;
        private readonly IProductExpressDao _productExpressDao;
        private readonly IConfiguration _configuration;
        private readonly IMemoryCache _memoryCache;

        public ProductShopService(IProductShopDao productShopDao
            , IProductService productService
            , IKwaiXiaoDianService kwaiXiaoDianService
            , ILogger<ProductShopService> logger
            , IProductExpressDao productExpressDao
            , IConfiguration configuration
            , IMemoryCache memoryCache) : base(productShopDao)
        {
            _productShopDao = productShopDao;
            _productService = productService;
            _kwaiXiaoDianService = kwaiXiaoDianService;
            _logger = logger;
            _productExpressDao = productExpressDao;
            _configuration = configuration;
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 获取商品的店铺信息
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public ShopInfo GetShopInfo(string productId, string distributeItemId)
        {
            ShopInfo shopInfo = new ShopInfo();
            var now = DateTime.Now;

            //读取缓存
            var cacheShopInfoHours = _configuration["Cache.ShopInfo.Hours"].ToInt(24);
            var cacheKey = string.Format("KwaiXiaoDian:Product:ShopInfo:{0}", distributeItemId);
            var cacheValue = _memoryCache.Get(cacheKey);
            if (cacheValue != null)
            {
                shopInfo = (ShopInfo)cacheValue;
                return shopInfo;
            }

            //从商品详情接口(缓存)获取，然后更新本地数据
            var getProductDetailInfoResult = _kwaiXiaoDianService.GetProductDetailInfo(distributeItemId, millisecondsTimeout: 1000);
            if (!getProductDetailInfoResult.IsSuccess)
            {
                //记录日志
                _logger.LogError(string.Format("获取商品的详情信息时发生异常，Message：{0}", getProductDetailInfoResult.ErrorMessage));
                return shopInfo;
            }

            Mtp_Storeentrance_Njfhtgf7qks5atfq storeInfo = new Mtp_Storeentrance_Njfhtgf7qks5atfq();//店铺信息
            var jObj = getProductDetailInfoResult.Data.data.data;
            foreach (var item in jObj)
            {
                if (item.Key.Contains("mtp_storeEntrance"))
                {
                    storeInfo = item.Value.ToObject<Mtp_Storeentrance_Njfhtgf7qks5atfq>();
                }
            }

            //平台下架的商品本地不删除，包括商品详情（物流和店铺信息）和达人排行榜数据
            if (storeInfo != null && storeInfo.fields != null && storeInfo.fields.shopInfo != null && storeInfo.fields.shopInfo.shopId == 0)
            {
                //记录日志
                _logger.LogError(string.Format("获取商品的详情信息时发生异常，Message：{0}", "商品不存在或已下架！"));
                return shopInfo;
            }

            //商品店铺信息
            var shopInfo2 = storeInfo.fields.shopInfo;
            Storescoreinfo summaryScoreInfo = shopInfo2.storeScoreInfo;
            var productScoreInfo = shopInfo2.storeScoreInfo.storeScoreQuadrantList.FirstOrDefault(p => p.name == "商品体验");
            var expressScoreInfo = shopInfo2.storeScoreInfo.storeScoreQuadrantList.FirstOrDefault(p => p.name == "物流体验");
            var serviceScoreInfo = shopInfo2.storeScoreInfo.storeScoreQuadrantList.FirstOrDefault(p => p.name == "售后服务");

            //不存在则新增，存在则更新
            var productShop = _productShopDao.Get(p => p.ProductId == productId).FirstOrDefault();
            if (productShop == null)
            {
                _productShopDao.Add(new TProductShop
                {
                    CreatedBy = -1,
                    CreatedTime = now,
                    LastUpdatedBy = -1,
                    LastUpdatedTime = now,
                    ProductId = productId,
                    ShopId = shopInfo2.shopId.ToString(),
                    ShopName = shopInfo2.shopName,
                    ShopIconUrl = shopInfo2.shopIconUrl,
                    DistributeSoldAmount = shopInfo2.distributeSoldAmount.ToInt(),
                    SoldAmountTabText = shopInfo2.soldAmountTabText,
                    SummaryScore = summaryScoreInfo.score.ToDecimalOrNull(),
                    SummaryRank = summaryScoreInfo.rank.ToString("0.00").ToDecimalOrNull(),
                    SummaryLevel = summaryScoreInfo.level,
                    ProductScore = productScoreInfo != null ? productScoreInfo.score.ToDecimalOrNull() : null,
                    ProductLevel = productScoreInfo != null ? productScoreInfo.level : "",
                    ExpressScore = expressScoreInfo != null ? expressScoreInfo.score.ToDecimalOrNull() : null,
                    ExpressLevel = expressScoreInfo != null ? expressScoreInfo.level : "",
                    ServiceScore = serviceScoreInfo != null ? serviceScoreInfo.score.ToDecimalOrNull() : null,
                    ServiceLevel = serviceScoreInfo != null ? serviceScoreInfo.level : ""
                });
            }
            else
            {
                productShop.LastUpdatedBy = -1;
                productShop.LastUpdatedTime = now;
                productShop.ShopId = shopInfo2.shopId.ToString();
                productShop.ShopName = shopInfo2.shopName;
                productShop.ShopIconUrl = shopInfo2.shopIconUrl;
                productShop.DistributeSoldAmount = shopInfo2.distributeSoldAmount.ToInt();
                productShop.SoldAmountTabText = shopInfo2.soldAmountTabText;
                productShop.SummaryScore = summaryScoreInfo.score.ToDecimalOrNull();
                productShop.SummaryRank = summaryScoreInfo.rank.ToString("0.00").ToDecimalOrNull();
                productShop.SummaryLevel = summaryScoreInfo.level;
                productShop.ProductScore = productScoreInfo != null ? productScoreInfo.score.ToDecimalOrNull() : null;
                productShop.ProductLevel = productScoreInfo != null ? productScoreInfo.level : "";
                productShop.ExpressScore = expressScoreInfo != null ? expressScoreInfo.score.ToDecimalOrNull() : null;
                productShop.ExpressLevel = expressScoreInfo != null ? expressScoreInfo.level : "";
                productShop.ServiceScore = serviceScoreInfo != null ? serviceScoreInfo.score.ToDecimalOrNull() : null;
                productShop.ServiceLevel = serviceScoreInfo != null ? serviceScoreInfo.level : "";
                _productShopDao.Update(productShop);
            }

            //设置返回结果
            //shopInfo.Id = productShop2.Id;
            //shopInfo.CreatedTime = productShop2.CreatedTime.ToString(DateTimeTypeConst.DATETIME);
            shopInfo.ProductId = productId;
            shopInfo.ProductName = _productService.GetProductName(productId);
            shopInfo.ShopId = shopInfo2.shopId.ToString();
            shopInfo.ShopName = shopInfo2.shopName;
            shopInfo.ShopIconUrl = shopInfo2.shopIconUrl;
            shopInfo.DistributeSoldAmount = shopInfo2.distributeSoldAmount;
            shopInfo.SoldAmountTabText = shopInfo2.soldAmountTabText;
            shopInfo.SummaryScore = summaryScoreInfo.score;
            shopInfo.SummaryRank = summaryScoreInfo.rank.ToString("0.00");
            shopInfo.SummaryLevel = summaryScoreInfo.level;
            shopInfo.ProductScore = productScoreInfo != null ? productScoreInfo.score : null;
            shopInfo.ProductLevel = productScoreInfo != null ? productScoreInfo.level : "";
            shopInfo.ExpressScore = expressScoreInfo != null ? expressScoreInfo.score : null;
            shopInfo.ExpressLevel = expressScoreInfo != null ? expressScoreInfo.level : "";
            shopInfo.ServiceScore = serviceScoreInfo != null ? serviceScoreInfo.score : null;
            shopInfo.ServiceLevel = serviceScoreInfo != null ? serviceScoreInfo.level : "";

            //设置缓存
            _memoryCache.Set(cacheKey, shopInfo, DateTimeOffset.Now.AddHours(cacheShopInfoHours));

            return shopInfo;
        }

    }
}
